package m3_publish_subscribe;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.UUID;

public class Consumer {
    public static void main(String[] args) throws Exception {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.64.140");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");

        Channel channel = connectionFactory.newConnection().createChannel();

        //1.定义随机队列  2.定义交换机  3.绑定
        //随机命名, 非持久, 独占, 自动删除
        String uuid = UUID.randomUUID().toString();
        channel.queueDeclare(
                uuid,
                false,
                true,
                true,
                null);

        //定义交换机
        channel.exchangeDeclare("logs", BuiltinExchangeType.FANOUT);

        //绑定交换机和队列
        channel.queueBind(
                uuid,       //队列
                "logs", //交换机
                "");    //该参数对fanout交换机无效

        // 正常的消费数据
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                String msg = new String(delivery.getBody());
                System.out.println("收到:"+msg);
            }
        };

        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {

            }
        };

        channel.basicConsume(uuid, true, deliverCallback, cancelCallback);
    }
}
